#include "get_bmp_path.h"

LINK_NODE *node_create(char *bmp_path) {
    LINK_NODE *node = (LINK_NODE *)malloc(sizeof(LINK_NODE));
    if (node == NULL) {
        perror("malloc");
        return NULL;
    }
    node->prev = NULL;
    node->next = NULL;
    node->data = (char *)malloc(strlen(bmp_path) + 1);
    if (node->data == NULL) {
        perror("malloc");
        free(node);
        return NULL;
    }
    strcpy(node->data, bmp_path); // 字符串拷贝函数, 把bmp_path保存的字符串拷贝到pnew->data
    return node;
}

LINK_LIST *list_create() {
    LINK_LIST *head = (LINK_LIST *)malloc(sizeof(LINK_LIST));
    if (head == NULL) {
        perror("malloc");
        return NULL;
    }
    head->end = NULL;
    head->first = NULL;
    head->num = 0;
    return head;
}

void add_node(LINK_LIST *head, LINK_NODE *pnew) {
    if (head->end == NULL && head->first == NULL) {
        head->first = pnew;
        head->end = pnew;
        pnew->prev = NULL;
        pnew->next = NULL;
    } else {
        pnew->prev = head->end;
        pnew->next = head->first;
        head->end->next = pnew;
        head->first->prev = pnew;
        head->end = pnew;
    }
    head->num++;
}

void remove_node(LINK_NODE *node) {
    if (node == NULL) return;
    if (node->prev != NULL) node->prev->next = node->next;
    if (node->next != NULL) node->next->prev = node->prev;
    free(node->data);
    free(node);
}

void delete_head(LINK_LIST *head) {
    while (head->first != head->end) {
        LINK_NODE *node = head->first;
        head->first = head->first->next;
        free(node->data);
        free(node);
    }
    free(head->end->data);
    free(head->end);
    free(head);
    printf("delete_head\n");
}

void show_path(LINK_LIST *head) {
    int num = head->num;
    LINK_NODE *p = head->first;
    while (num--) {
        printf("-----------%s\n", p->data);
        p = p->next;
    }
}

int get_bmp_path(char *path, LINK_LIST *head) {
    DIR *dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }
    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue;
        char buffer[1024];
        sprintf(buffer, "%s/%s", path, entry->d_name);
        struct stat st;
        if (stat(buffer, &st) == -1) {
            perror("stat");
            closedir(dir);
            return 1;
        }
        if (S_ISREG(st.st_mode) && strcmp(entry->d_name + strlen(entry->d_name) - 4, ".bmp") == 0) {
            LINK_NODE *node = node_create(buffer);
            if (node != NULL) add_node(head, node);
        }
        if (S_ISDIR(st.st_mode)) get_bmp_path(buffer, head);
    }
    closedir(dir);
    return 0;
}

